package wordit.impl.letterCells;

import wordit.Game;
import wordit.ea.Genome;
import wordit.ea.MutationFunction;

public class LetterCellMutation implements MutationFunction {

	private double mutationProbability;
	private int numOfCells;
	
	public LetterCellMutation (Game game, double mutationProbability) {
		numOfCells = game.getNumOfColumns() * game.getNumOfRows();
		this.mutationProbability = mutationProbability;
	}
	
	@Override
	public Genome mutateGenom(Genome gen) {
		if (Math.random() >= getMutationProbability())
			return gen;

		LetterCellGenome LCGenome = (LetterCellGenome) gen;	
		int randomIndex = (int) Math.floor(
				Math.random() * LCGenome.getNumOfLetterCells());
		LetterCell oldCell = LCGenome.getLetterCellAt(randomIndex);
		
		int vacantLocation;
		
		do {
			vacantLocation = (int) (Math.random() * numOfCells);
		} while (LCGenome.getLetterAt(vacantLocation)!=null);
		
		LCGenome.setLetterCellAt(randomIndex, new LetterCell (oldCell.getLetter(), vacantLocation));
		
		return LCGenome;
	}

	public void setMutationProbability(double mutationProbability) {
		this.mutationProbability = mutationProbability;
	}

	public double getMutationProbability() {
		return mutationProbability;
	}
}
